#pragma once
#include <iostream>
#include <memory>
#include "Socket.hpp"
#include "Connection.hpp"

//处理监听套接字连接的fd
// 该类未来统一进行listensock的管理工作，获取新连接

using namespace socket_ns;

class Listener
{
public:
    Listener(uint16_t port) : _port(port), _listensock(std::make_unique<TcpSocket>())
    {
        _listensock->BuildListenSocket(_port);
    }
    int ListenSockfd()
    {
        return _listensock->Sockfd();
    }
    void Accepter(Connection *conn)
    {
        while (true)
        {
            errno = 0;
            InetAddr addr;
            int code = 0;
            int sockfd = _listensock->Accepter(&addr, &code);
            if (sockfd > 0)
            {
                // 该socket获取成功了，我们该怎么办？？
                LOG(INFO, "获取连接成功, 客户端: %s:%d, sockfd: %d\n", addr.Ip().c_str(), addr.Port(), sockfd);
                conn->_R->AddConnection(sockfd, EPOLLIN|EPOLLET, addr, NormalConnection);
            }
            else
            {
                if (code == EWOULDBLOCK)
                {
                    LOG(INFO, "底层连接全部获取完毕\n");
                    break;
                }
                else if (code == EINTR)
                {
                    continue;
                }
                else
                {
                    LOG(ERROR, "获取连接失败.!\n");
                    break;
                }
            }
        }
    }
    ~Listener()
    {
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
};